package com.gitee.wsl.platform.exception

internal actual fun Throwable.isFatal(): Boolean =
    (this is VirtualMachineError) ||
            (this is ThreadDeath) ||
            (this is LinkageError)


internal actual fun createDefaultUncaughtErrorHandler(): (Throwable) -> Unit = { e ->
    Thread
        .currentThread()
        .also { thread ->
            thread
                .uncaughtExceptionHandler
                ?.uncaughtException(thread, e)
        }
}

fun Throwable?.rethrowIfFatal() {
    val e = this
    if (e is StackOverflowError) {
        // Stack-overflows should be reported as-is, instead of crashing
        // the process
        return
    }
    if (e is Error) {
        throw e
    }
}

fun Throwable?.logOrRethrow( ) {
    val e = this
    rethrowIfFatal()
    val thread = Thread.currentThread()
    var logger = thread.uncaughtExceptionHandler
    if (logger == null) {
        logger = Thread.getDefaultUncaughtExceptionHandler()
    }
    if (logger == null) {
        logger = Thread.UncaughtExceptionHandler { t: Thread?, e1: Throwable? -> e1!!.printStackTrace(System.err) }
    }
    logger.uncaughtException(thread, e)
}